function observer (data) {
    if (!data || typeof data !== 'object') return
    return new Observer(data)
}

function Observer (data) {
    this.data = data
    this.init(data)
}

Observer.prototype = {
    init: function (data) {
        Object.keys(data).forEach(key => {
            this.defineReactive(data, key, data[key])
        })
    },
    defineReactive (data, key, val) {
        let dep = new Dep()

        observer(val)

        Object.defineProperty(data, key, {
            enumerable: true, //可以枚举
            configurable: false, //不可以重新定义
            get: function () {
                if (Dep.target) {
                    dep.depend()
                }
                return val
            },
            set: function (newVal) {
                if (newVal === val) return
                val = newVal
                dep.notify()
            }
        })
    }
}

let uid = 0
function Dep () {
    this.id = uid++
    this.subs = []
}
Dep.prototype = {
    depend: function () {
        Dep.target.addDep(this)
    },
    addSub: function (sub) {
        this.subs.push(sub)
    },
    notify: function () {
        this.subs.forEach(sub => {
            sub.update()
        })
    }
}
Dep.target = null